﻿using System;
using HashFoo.Rest.Common;
using Newtonsoft.Json;

namespace HashFoo.Rest.Serializers.JsonNet
{
    /// <summary>
    /// Serailizes resources using simple JSON.NET serialization.
    /// </summary>
    public class JsonNetResourceSerializer : IResourceSerializer
    {
        private const string JsonMimeType = "application/json";

        /// <summary>
        /// Default constructor with default settings.
        /// </summary>
        public JsonNetResourceSerializer()
            : this(null)
        {
        }

        /// <summary>
        /// Constructor with custom serialization settings.
        /// </summary>
        /// <param name="settings"></param>
        public JsonNetResourceSerializer(JsonSerializerSettings settings)
        {
            Settings = settings;
        }

        /// <summary>
        /// The serialization settings that will be used.
        /// </summary>
        public JsonSerializerSettings Settings { get; set; }

        #region IResourceSerializer Members

        /// <summary>
        /// The MIME types this serializer will accept
        /// </summary>
        public string[] AcceptMimeTypes
        {
            get { return new[] {JsonMimeType}; }
        }

        /// <summary>
        /// The MIME type to which content is serialized.
        /// </summary>
        public string ContentMimeType
        {
            get { return JsonMimeType; }
        }

        /// <summary>
        /// Reads an object from a string.
        /// </summary>
        /// <typeparam name="T">The type of object to be returned</typeparam>
        /// <param name="data">The string data to deserialize into the object</param>
        /// <returns>The deserialized object.</returns>
        public T Read<T>(string data)
        {
            return JsonConvert.DeserializeObject<T>(data, Settings);
        }

        public object Read(string data, Type type)
        {
            return JsonConvert.DeserializeObject(data, type, Settings);
        }

        /// <summary>
        /// Write an object to a serialized string.
        /// </summary>
        /// <typeparam name="T">The type of object to serialize.</typeparam>
        /// <param name="data">The data to serialize.</param>
        /// <returns>The serialized data string.</returns>
        public string Write<T>(T data)
        {
            return JsonConvert.SerializeObject(data, Settings);
        }

        #endregion
    }
}